package cn.cl.gulimall.ware.service.impl;

import cn.cl.common.constant.WareConstant;
import cn.cl.common.utils.R;
import cn.cl.gulimall.ware.entity.PurchaseDetailEntity;
import cn.cl.gulimall.ware.service.PurchaseDetailService;
import cn.cl.gulimall.ware.service.WareSkuService;
import cn.cl.gulimall.ware.vo.MergeVo;
import cn.cl.gulimall.ware.vo.PurchaseDoneVo;
import cn.cl.gulimall.ware.vo.PurchaseItemDoneVo;
import lombok.NonNull;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.cl.common.utils.PageUtils;
import cn.cl.common.utils.Query;

import cn.cl.gulimall.ware.dao.PurchaseDao;
import cn.cl.gulimall.ware.entity.PurchaseEntity;
import cn.cl.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		IPage<PurchaseEntity> page = this.page(
				new Query<PurchaseEntity>().getPage(params),
				new QueryWrapper<PurchaseEntity>()
		);

		return new PageUtils(page);
	}

	/**
	 * 未完成的采购需求
	 */
	@Override
	public PageUtils queryPageUnreceive(Map<String, Object> params) {
		IPage<PurchaseEntity> page = this.page(
				new Query<PurchaseEntity>().getPage(params),
				new QueryWrapper<PurchaseEntity>()
						.eq("status", 0)
						.or()
						.eq("status", 1)
		);
		return new PageUtils(page);
	}


	@Autowired
	private PurchaseDetailService purchaseDetailService;

	/**
	 * 合并采购细求
	 */
	@Transactional
	@Override
	public void mergePurchase(MergeVo mergeVo) {
		Long purchaseId = mergeVo.getPurchaseId();
		if (purchaseId == null) {
			PurchaseEntity purchaseEntity = new PurchaseEntity();
			purchaseEntity.setCreateTime(new Date());
			purchaseEntity.setUpdateTime(new Date());
			purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
			this.save(purchaseEntity);
			purchaseId = purchaseEntity.getId();
		}
		List<Long> items = mergeVo.getItems();
		if (items != null && items.size() > 0) {
			Long finalPurchaseId = purchaseId;
			List<PurchaseDetailEntity> purchaseDetailEntities = items.stream().map((item) -> {
				PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
				purchaseDetailEntity.setId(item);
				purchaseDetailEntity.setPurchaseId(finalPurchaseId);
				purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
				return purchaseDetailEntity;
			}).filter((purchaseDetailEntity) -> {
				// 检查只有采购状态为 0 和 1 才可以进行合并
				return purchaseDetailEntity.getStatus() == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode() ||
						purchaseDetailEntity.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode();
			}).collect(Collectors.toList());
			purchaseDetailService.updateBatchById(purchaseDetailEntities);
		}
	}


	/**
	 * 领取采购单
	 */
	@Transactional
	@Override
	public void received(List<Long> ids) {
		// 1、确认当前采购单是新建或者是已分配状态
		List<PurchaseEntity> purchaseEntities = ids.stream().map((id) -> {
			PurchaseEntity purchaseEntity = this.getById(id);
			return purchaseEntity;
		}).filter((purchaseEntity) -> {
			return purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
					purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode();
		}).map((purchaseEntity) -> {
			purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
			purchaseEntity.setUpdateTime(new Date());
			return purchaseEntity;
		}).collect(Collectors.toList());
		// 2、改变采购单的状态
		this.updateBatchById(purchaseEntities);
		// 3、 改变采购项的状态
		purchaseEntities.forEach((purchaseEntitie) -> {
			List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listDateilByPurchaseId(purchaseEntitie.getId());
			if (purchaseDetailEntities != null && purchaseDetailEntities.size() > 0) {
				List<PurchaseDetailEntity> purchaseDetailEntityList = purchaseDetailEntities.stream().map((item) -> {
					PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
					purchaseDetailEntity.setId(item.getId());
					purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
					return purchaseDetailEntity;
				}).collect(Collectors.toList());
				purchaseDetailService.updateBatchById(purchaseDetailEntityList);
			}
		});
	}


	@Autowired
	private WareSkuService wareSkuService;

	/**
	 * 完成采购单
	 */
	@Override
	public void done(PurchaseDoneVo purchaseDoneVo) {
		// 1、 改变采购项状态
		Long id = purchaseDoneVo.getId();
		boolean flag = true;
		List<PurchaseItemDoneVo> purchaseItemDoneVos = purchaseDoneVo.getItems();
		List<PurchaseDetailEntity> updates = new ArrayList<>();
		for (PurchaseItemDoneVo purchaseItemDoneVo : purchaseItemDoneVos) {
			PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
			if (purchaseItemDoneVo.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
				flag = false;
				purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());
			} else {
				purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
				// 2、将成功采购的进行入库
				PurchaseDetailEntity purchaseDetailServiceById = purchaseDetailService.getById(purchaseItemDoneVo.getItemId());
				if (purchaseDetailServiceById != null) {
					wareSkuService.addStock(purchaseDetailServiceById.getSkuId(), purchaseDetailServiceById.getWareId(), purchaseDetailServiceById.getSkuNum());
				} else {
					log.error("采购信息有误，入库失败");
					return;
				}
			}
			purchaseDetailEntity.setId(purchaseItemDoneVo.getItemId());
			updates.add(purchaseDetailEntity);
		}
		purchaseDetailService.updateBatchById(updates);

		// 3、 改变采购单状态
		PurchaseEntity purchaseEntity = new PurchaseEntity();
		purchaseEntity.setId(id);
		purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
		purchaseEntity.setUpdateTime(new Date());
		this.updateById(purchaseEntity);
	}
}